#author : wx
#json to c# class

import sys
import json
import os

Indir = "./"
Outdir = "./"


def parse_json(jsonFile):
    code = "//此文件自动生成，不要修改\n"
    code += "\nnamespace AutoJsonClass\n{"
    code += "\n\tpublic class "

    strs = jsonFile.split('.')
    suf = "Error"
    if len(strs) > 0 :
        code += strs[0]
        suf = strs[0]
        code += "\n\t{"
    else:
        print("文件名出错")
        return
    
    with open(os.path.join(Indir,jsonFile),'r',encoding='utf-8') as f:
        s = f.read()
        datas = json.loads(json.dumps(eval(s)))

        for data in datas:
            for k,v in data.items():
                #int float string
                code += "\n\t\tpublic "
                
                #根据|区分类型
                strSplite = k.split('|',1)
                if len(strSplite) == 1:  #没有|，大致判断
                    strType = "string "
                    if type(v) == int :
                        strType = "int "

                    if type(v) == float :
                        strType = "float "
                    code += strType 
                    code += k
                elif len(strSplite) > 1:
                    code += strSplite[0]
                    code += " "
                    code += strSplite[1]
                else :
                    continue

                code += " { get; set; }"
            code += "\n\t}\n}"
            break
        fileNameAll = suf+".cs"

        r=open(os.path.join(Outdir,fileNameAll),"x",encoding='utf-8')
        r.write(code)
        r.close

        print("创建 {0} 完成!".format(fileNameAll))

if __name__ == '__main__':
    num = len(sys.argv)
    Indir = sys.argv[1]
    Outdir = sys.argv[2]
    jsonFiles = []
    files = os.listdir(Indir)
    for file in files:
        if file.endswith('json'):
            jsonFiles.append(file)

    print ("正在删除目标目录{0}下所有文件!".format(os.path.abspath(Outdir)))

    deleFiles = os.listdir(Outdir)
    for file in deleFiles:
        os.remove(os.path.join(Outdir,file))
        print("删除{0}".format(file))
    
    print ("\n当前目录有{0}个json文件,开始创建...".format(len(jsonFiles)))
    for jsonFile in jsonFiles:
        parse_json(jsonFile)